/*================================================================
*   Copyright (C) 2018  All rights reserved.
*   
*   Filename：udp_server.c
*   Creator ：pony
*   Create  date：2018-01-28
*   Description：
*
================================================================*/

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>

#define MAXBYTES 80 
int main(int argc,char** argv)
{
	struct sockaddr_in servaddr;
    struct sockaddr_in cliaddr;
	socklen_t cliaddr_len;
	int sockfd;
	char buff[MAXBYTES];
    char str[INET_ADDRSTRLEN];
	int len;

	sockfd = socket(AF_INET,SOCK_DGRAM,0);
	bzero(&servaddr,sizeof(servaddr));

	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(6666);

	//bind
	bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
	printf("Accepting connections...\n");

	while(1)
	{
		cliaddr_len = sizeof(cliaddr);
		len = recvfrom(sockfd,buff,MAXBYTES,0,(struct sockaddr*)&cliaddr,&cliaddr_len);
		if(len != -1)
		{
			printf("recvived from %s at PORT%d :[%d] %s\n",
					inet_ntop(AF_INET,&cliaddr.sin_addr,str,sizeof(str)),
					ntohs(cliaddr.sin_port),len,buff);
		}

	}

	close(sockfd);
	return 0;
}
